#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: crud.py
# @time: 2021/5/18 13:31
# @desc:
import json
from typing import *

import redis
import pymongo
from deprecated import deprecated

from configs import *


def get_history_clamp_in_all_scene():
    """
    # 获取所有场景中包含的所有历史夹具的id

    :return:
    """
    result = []
    scenes = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    for i in scenes:
        if "historyClamp" in i.keys() and type(i["historyClamp"]) is list:
            result.extend(i["historyClamp"])
    return list(set(result))


def get_standard_clamp_in_all_scene():
    """
    # 获取所有场景中包含的所有标准夹具的id

    :return:
    """
    result = []
    scenes = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    for i in scenes:
        if "standardClamp" in i.keys() and type(i["standardClamp"]) is list:
            result.extend(i["standardClamp"])
    return list(set(result))


def retrieve_one_mongo_value(
        number: str,
        collection_name: str,
        database_name: str = MONGO_DATABASE_NAME,
        url: str = MONGO_URL,
) -> List:
    """
    输入number，查询数据，返回的是一个只有一条数据的列表（理论上），如果列表不止一条数据，那么说明数据库里id不唯一，有问题了。

    :param number:
    :param url:
    :param database_name:
    :param collection_name:
    """
    myclient = pymongo.MongoClient(url)
    mydb = myclient[database_name]
    mycol = mydb[collection_name]
    result = []
    for i in mycol.find({"number": number}):
        i.pop("_id")
        result.append(i)
    return result


def retrieve_all_mongo_values(
        filter_conditions: Dict,
        collection_name: str,
        database_name: str = MONGO_DATABASE_NAME,
        url: str = MONGO_URL,
) -> List:
    """
    输入查询条件查询数据，返回的是一堆元素为字典数据的列表（理论上）。
    如果根据number查询到的列表不止一条数据，那么说明数据库里id不唯一，有问题了。

    :param data_type:
    :param filter_conditions:
    :param url:
    :param database_name:
    :param collection_name:
    """
    myclient = pymongo.MongoClient(url)
    mydb = myclient[database_name]
    mycol = mydb[collection_name]
    result = []
    for i in mycol.find(filter_conditions):
        i.pop("_id")
        result.append(i)
    return result


def get_scene_by_history_clamp(history_clamp_number: str, scenes: list):
    for i in scenes:
        if "historyClamp" in i.keys() and i["historyClamp"] is not None and history_clamp_number in i["historyClamp"]:
            return i["number"]


def update(data_type: str, collection_name: str):
    """
    去mongo中取数据来更新redis中的数据。

    :param data_type:
    :param collection_name:
    """
    redis_connection = redis.StrictRedis(host=REDIS_IP, port=REDIS_PORT, db=0)
    data = retrieve_all_mongo_values({}, collection_name=collection_name)
    data_keys = [i["number"] for i in data]
    redis_connection.set(data_type, json.dumps(data_keys))
    for i in data:
        redis_connection.set(i["number"], json.dumps(i))


def extract_history_clamp_from_mongo_to_redis():
    """
    从mongo中取历史夹具的数据，更新到redis上。

    """
    scene_history_clamp_list = get_history_clamp_in_all_scene()
    redis_connection = redis.StrictRedis(host=REDIS_IP, port=REDIS_PORT, db=0)
    scenes = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    data = retrieve_all_mongo_values({}, collection_name=HISTORY_CLAMP_COLLECTION)
    data_keys = [i["number"] for i in data]
    redis_connection.set("history_clamp", json.dumps(data_keys))
    for i in data:
        if i["number"] in scene_history_clamp_list:
            i["isSceneBinded"] = True
            i["scene"] = get_scene_by_history_clamp(i["number"], scenes)
        else:
            i["isSceneBinded"] = False
        redis_connection.set(i["number"], json.dumps(i))


def extract_standard_clamp_from_mongo_to_redis():
    """
    从mongo中取标准夹具的数据，更新到redis上。

    """
    scene_standard_clamp_list = get_standard_clamp_in_all_scene()
    redis_connection = redis.StrictRedis(host=REDIS_IP, port=REDIS_PORT, db=0)
    data = retrieve_all_mongo_values({}, collection_name=STANDARD_CLAMP_COLLECTION)
    data_keys = [i["number"] for i in data]
    redis_connection.set("standard_clamp", json.dumps(data_keys))
    for i in data:
        if i["number"] in scene_standard_clamp_list:
            i["isSceneBinded"] = True
        else:
            i["isSceneBinded"] = False
        redis_connection.set(i["number"], json.dumps(i))


@deprecated
def update_scene():
    """
    更新场景数据。

    """
    redis_connection = redis.StrictRedis(host=REDIS_IP, port=REDIS_PORT, db=0)
    data = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    data_keys = [i["number"] for i in data]
    redis_connection.set("scene", json.dumps(data_keys))
    for i in data:
        redis_connection.set(i["number"], json.dumps(i))


# deprecated
def update_scene_data_board():
    redis_connection = redis.StrictRedis(host=REDIS_IP, port=REDIS_PORT, db=0)
    data = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    new_data = []
    for i in data:
        temp_item = {
            "number": i["number"],
            "name": i["name"],
            "desc": i["desc"],
        }
        try:
            history_clamp_example = retrieve_one_mongo_value(i["historyClamp"][0], collection_name=HISTORY_CLAMP_COLLECTION)[0]
        except:
            continue
        temp_item["historyClampQuantity"] = len(i["historyClamp"])
        temp_item["standardClampQuantity"] = len(i["standardClamp"])
        temp_item["rpsNumber"] = history_clamp_example["tag"]["rpsNumber"]
        temp_item["pinNumber"] = len(history_clamp_example["tag"]["pinType"])
        new_data.append(temp_item)
    new_data = sorted(new_data, key=lambda x: int(x["name"]))
    redis_connection.set("data_board_scene", json.dumps(new_data))


def udpate_history_clamp_data_board():
    redis_connection = redis.StrictRedis(host=REDIS_IP, port=REDIS_PORT, db=0)
    data = retrieve_all_mongo_values({}, collection_name=HISTORY_CLAMP_COLLECTION)
    new_data = []
    for i in data:
        temp_item = {
            "number": i["number"],
            "name": i["name"],
            "desc": i["desc"],
            "rpsNumber": i["tag"]["rpsNumber"],
            "rpsType": i["tag"]["rpsType"],
            "airNumber": i["tag"]["airNumber"],
            "area": i["tag"]["area"],
        }
        new_data.append(temp_item)
    new_data = sorted(new_data, key=lambda x: x["name"][:2])
    redis_connection.set("data_board_history_clamp", json.dumps(new_data))


def extract_scene_to_redis():
    redis_connection = redis.StrictRedis(host=REDIS_IP, port=REDIS_PORT, db=0)
    data = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    data = sorted(data, key=lambda x: int(x["name"]))
    data_numbers = [i["number"] for i in data]
    data_names = [i["name"] for i in data]
    data_descs = [i["desc"] for i in data]
    redis_connection.set("scene", json.dumps(data_numbers))
    redis_connection.set("scene_name", json.dumps(data_names))
    redis_connection.set("scene_desc", json.dumps(data_descs))

    new_data = []
    for i in data:
        if i["historyClamp"] is None:
            i["historyClamp"] = []
        if i["standardClamp"] is None:
            i["standardClamp"] = []
        redis_connection.set(i["name"], json.dumps(i))
        redis_connection.set(i["number"], json.dumps(i))
        temp_item = {
            "number": i["number"],
            "name": i["name"],
            "desc": i["desc"],
        }
        try:
            history_clamp_example = retrieve_one_mongo_value(i["historyClamp"][0], collection_name=HISTORY_CLAMP_COLLECTION)[0]
        except:
            continue
        temp_item["historyClampQuantity"] = len(i["historyClamp"])
        temp_item["standardClampQuantity"] = len(i["standardClamp"])
        temp_item["rpsNumber"] = history_clamp_example["tag"]["rpsNumber"]
        temp_item["pinNumber"] = len(history_clamp_example["tag"]["pinType"])
        new_data.append(temp_item)

    redis_connection.set("data_board_scene", json.dumps(new_data))


if __name__ == '__main__':
    data = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    print(**{i["number"]: json.dumps(i) for i in data})
